package com.shengruan.admin.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.shengruan.admin.vo.BidHistory;
import com.shengruan.framework.jdbc.BaseJdbc;
import com.shengruan.framework.jdbc.BeanListHandler;


public class BidHistoryJdbc extends BaseJdbc {

   
    public static final String BIDHISTORY_INSERT = "INSERT INTO bidhistory (TYPE, biddingCount, userId, creationTime)VALUES(?, ?, ?, ?)";


    public void save(BidHistory bidhistory) {
        Connection conn = this.getConnection();
        Object[] pram = {bidhistory.getType(), bidhistory.getBiddingCount(), bidhistory.getUserId(), bidhistory.getCreationTime()};
        try {
            this.execute(conn, BIDHISTORY_INSERT, pram);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.close(conn);
        }
    }

    public boolean isSecondBidding(int userId) {
        Connection conn = this.getConnection();
        StringBuilder sql = new StringBuilder("select count(bh.id) from bidhistory bh where bh.type = ? and bh.userId = ?");
        Object[] pram = {1, userId};
        int count = 0;
        try {
            count = this.getRows(conn, sql.toString(), pram);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.close(conn);
        }
        if (count == 1) {
            return true;
        } else {
            return false;
        }
    }

    public int getSumByUserIdAndType(int userId, int type) {
        Connection conn = this.getConnection();
        StringBuilder sql = new StringBuilder("select SUM(bh.biddingCount) from bidhistory bh where bh.type = ? and bh.userId = ?");
        Object[] pram = {type, userId};
        int count = 0;
        try {
            count = this.getRows(conn, sql.toString(), pram);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.close(conn);
        }
        return count;
    }


    public BidHistory getByUserId(int userId) {
        List<BidHistory> bidhistoryList = new ArrayList<BidHistory>();
        Connection conn = this.getConnection();
        StringBuilder sql = new StringBuilder("select * from bidhistory bh where bh.type = ? and bh.userId = ?");
        Object[] pram = {1, userId};

        try {
            bidhistoryList = this.query(conn, sql.toString(), new BeanListHandler<BidHistory>(BidHistory.class), pram);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.close(conn);
        }

        if (CollectionUtils.isNotEmpty(bidhistoryList))
            return bidhistoryList.get(0);
        else
            return null;
    }
}
